package org.marsdonne.commons.jpa;

import lombok.Getter;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import java.time.LocalDate;

@Getter
public class LocalDateFieldFilter extends BasedFieldFilter {
    private LocalDate startWith;
    private LocalDate endWith;

    public LocalDateFieldFilter() {
        this.endWith = LocalDate.now();
        this.startWith = generateDefaultValueBy(this.endWith, -7);
    }

    public LocalDateFieldFilter(int amountOfDate) {
        this.endWith = LocalDate.now();
        this.startWith = generateDefaultValueBy(this.endWith, amountOfDate);
    }

    private LocalDate generateDefaultValueBy(LocalDate basedDate, int amountOfDate) {
        return basedDate.plusDays(amountOfDate);
    }

    public void setStartWith(LocalDate startWith) {
        this.startWith = startWith;
        if (this.endWith == null)
            this.endWith = generateDefaultValueBy(this.startWith, 7);
    }

    public void setEndWith(LocalDate endWith) {
        this.endWith = endWith;
        if (this.startWith == null)
            this.startWith = generateDefaultValueBy(this.endWith, -7);
    }

    @Override
    public Predicate generateCriteria(CriteriaBuilder builder, Path field) {
        return builder.between(field, startWith, endWith);
    }
}
